package com.example.administrator.rxjavarxandroid_retrofit.http.factory;

import com.example.administrator.rxjavarxandroid_retrofit.common.Constants;
import com.example.administrator.rxjavarxandroid_retrofit.http.api.CommonApi;
import com.example.administrator.rxjavarxandroid_retrofit.http.filter.AuthInterceptor;
import com.example.administrator.rxjavarxandroid_retrofit.http.filter.ResponseInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2016/12/14.
 */
public class RetrofitFactory {

    private static volatile RetrofitFactory mInstanse=null;

    public CommonApi mApi;

    public RetrofitFactory() {
        mApi = provideHotApi();
    }

    private OkHttpClient provideOkHttpClient() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(Constants.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                .connectTimeout(Constants.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                .addInterceptor(loggingInterceptor)
                .addInterceptor(new AuthInterceptor())
                .addInterceptor(new ResponseInterceptor())
                .build();

        return okHttpClient;
    }

    public CommonApi provideHotApi() {
        Retrofit retrofit1 = new Retrofit.Builder()
                .baseUrl(Constants.Base_Url)
                .client(provideOkHttpClient())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(new ApiErrorAwareConverterFactory(new EmptyJsonLenientConverterFactory(GsonConverterFactory.create())))
                //.addConverterFactory(GsonConverterFactory.create())
                .build();
      return retrofit1.create(CommonApi.class);
    }

    public static RetrofitFactory getmInstanse() {
        if(mInstanse==null){
            synchronized (RetrofitFactory.class){
                if(mInstanse==null){
                    mInstanse = new RetrofitFactory();
                }
            }
        }
        return mInstanse;
    }
}
